// APP
if (window.plus) {
    goodsDetailPageReady();
} else {
    document.addEventListener('plusready', goodsDetailPageReady, false);
}
// Web
$(function () {
    if (AGENT_CLIENT.WEB) {
        goodsDetailPageReady();
    }
})
// 初始化方法
function goodsDetailPageReady() {
    var _main = ("fixed" == $(".main").css("position")) ? $(".main") : $(window);
    var _goodsId = getUrlParam("id"); // 3365 6900130003010001
    var _shareId = getUrlParam("s"); // 1009330
    var _shareUid = getUrlParam("u"); // 15
    var _barcodetype = getUrlParam("type");
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
    var _contentheight = ($(window).height() - CONFIG_MANAGER.headerHight);
    var _online_sale = -1; //  0:新商品 1：上架 2:下架
    var goodsDetailPage = function () {
        this.init();
    };
    goodsDetailPage.prototype = {
        // 初始化页面
        init: function () {
            this.loadGoodsDetail();
            this.loadloveitemlist();
            this.bindEvent();
        },
        //加载商品信息
        loadGoodsDetail: function (data) {
            var model = this;
            var url = _barcodetype == 1 ? "v1/goods/sku/" : "v1/goods/";
            //商品详情
            var detailajax = $.ajax({
                type: "get",
                url: CONFIG_MANAGER.RequstUrl + url + _goodsId,
                beforeSend: function () {
                    $.showWaiting();
                }
            }).done(function (data) {
                _goodsId = data.sku_id;
                _online_sale = data.online_sale;
                
                _goodsCommentsPage.init(_goodsId);
                _sharePage.shareInfo = {
                    title: data.title,
                    content: data.name + data.specs,
                    href: CONFIG_MANAGER.shareUrl + "goods/goodsdetail.html?id=" + data.sku_id,
                    pic: getImageUrl(data.logo, 200, 200),
                    picid: data.logo
                };

                model.addBarcodeHistory(data);
                model.paintGoodsAlbums(data.Albums);
                model.paintGoodsDetail(data);
                model.bindGoodsEvent();
                model.loadCouponInfo(data.shop_id);
                model.loadPromoInfo(data);
                model.getCurrentRegion();
                model.checkFavorite();
                model.addhistory();
            }).fail(function () {
                $.alert("没找到该商品！", function () {
                    back();
                });
            }).always(function () {
                $.closeWaiting();
            });
            if (_currentloginuser && _currentloginuser.id) {
                var cacheproductcount = getLocalStorage(STORAGE_MANAGER.cacheproductcount);
                if (cacheproductcount && parseInt(cacheproductcount) > 0) {
                    $("#btnshopcart span").show().text(cacheproductcount);
                } else {
                    $("#btnshopcart span").hide().text(0);
                }
            }
        },
        // 绑定事件
        bindEvent: function () {
            //回退
            $("#back").on("click", function () {
                back();
            });
            // 置顶
            $("#gotop").on("click", function () {
                if (os.ios) {
                    _main.animate({
                        scrollTop: '0px'
                    }, 500);
                } else {
                    $("body, html").animate({
                        scrollTop: 0
                    }, 500);
                }
            });
            // 页面滚动
            _main.scroll(this.isDisplayTopIcon);
            // 更多
            $("#btnmore").on("click", function () {
                if ($("#morediv").css("display") == "none") {
                    $("#bgdiv").show();
                    $("#moredivicon").show();
                    $("#morediv").show();
                } else {
                    hidemore();
                }
            });
            // 更多菜单
            $("#moreli li").on("click", function () {
                var tip = $(this).attr("tip");
                if (tip == "0") {
                    if (AGENT_CLIENT.APP) {
                        plus.webview.getWebviewById("../home/main.html").evalJS("redirectTab(0)");
                    } else {
                        // 首页
                        redirect("../home/index.html");
                    }
                } else if (tip == "1") {
                    // 分享
                    _sharePage.show();
                } else if (tip == "2") {
                    // 搜索
                    showSearchPage();
                }
                hidemore();
            });
            // 猜你喜欢
            $("#loveitemlist").on("click", "li", function () {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });
            $("#bgdiv").on("click", function () {
                hidemore();
            });
            // 隐藏更多
            function hidemore() {
                $("#moredivicon").hide();
                $("#morediv").hide();
                $("#bgdiv").hide();
                $("#choosediv").removeClass("moveFromBottom-moved");
                setTimeout(function () {
                    $("#choosediv").hide();
                }, 300);
            };
        },
        // 商品绑定事件
        bindGoodsEvent: function () {
            // 点击轮播图全屏展示
            var touchmoveHander = function(event){ event.preventDefault(); };
            $("#banner").on("click", function () {
                if ($("#banner").hasClass("banner")) {
                    $("#gdmain").addClass("topdingwei");
                    $("#banner")[0].className = "banner-dingwei";
                    $("#tups")[0].className = "tups tups1";
                    if (AGENT_CLIENT.APP && os.ios) {
                        plus.navigator.setStatusBarBackground("rgba(0,0,0,0.97)");
                        plus.navigator.setStatusBarStyle('UIStatusBarStyleBlackOpaque');
                    }
										document.addEventListener('touchmove', touchmoveHander, true);                    
                } else {
                    $("#gdmain").removeClass("topdingwei");
                    $("#banner")[0].className = "banner";
                    $("#tups")[0].className = "tups";
                    if (AGENT_CLIENT.APP && os.ios) {
                        plus.navigator.setStatusBarBackground("#FEFEFE");
                        plus.navigator.setStatusBarStyle('UIStatusBarStyleDefault');
                    }
										document.removeEventListener('touchmove', touchmoveHander,true);                    
                }
                
            });
            // 懒加载
            $('img.lazy').lazyload({
                container: $(".main"),
                event: "scroll",
                threshold: 100,
                failure_limit: 10
            });
            // 懒加载
            $('img.lazy').lazyload({
                container: $("body,html"),
                event: "scroll",
                threshold: 100,
                failure_limit: 10
            });
            // 领优惠券
            $("#couponlist span").on("click", function () {
                var tip = $(this).attr("tip");
            });
            // 跳转套装
            $("#promolist").on("click", "#btnsuite", function () {
                redirect("../goods/suite.html?id=" + _goodsId);
            });
            // 送至
            $("#btnregion").on("click", function () {
                $("#detailpage").hide();
                _regionPage.show();
            });
            // 商品介绍Tab
            var currenttab = $("#currenttab");
            var directionstab = $("#directionstab span");
            currenttab.css({
                width: directionstab.width(),
                "margin-left": directionstab.offset().left,
                "margin-top": "-3px"
            });
            directionstab.on("click", function () {
                var tip = $(this).attr("tip");
                var activeli = $('#directionstab span[class=current]');
                if (activeli.attr("tip") == tip) {
                    return;
                }
                activeli.removeClass("current");
                $(this).addClass("current");
                var value = "translateX(" + $(this).offset().left + "px)";
                $("#currenttab").css({
                    "margin-left": "0px",
                    "transform": value,
                    "-webkit-transform": value,
                    "-o-transform": value,
                    "-ms-transform": value
                });
                $("div[name=tab]:visible").hide();
                $("#tab" + tip).show();
            });
            // 更多评价
            $("#btnmoreappraise").on("click", function () {
                var count = $("#btnmoreappraise span").text();
                if ("" == count) {
                    $.toast("暂无评论");
                    return;
                }
                $("#appraisepage").show(300);
                $("#detailpage").hide();
                _goodsCommentsPage.show();
            });
            // 进入店铺
            $("#btnentershop").on("click", function () {
                redirect("../shop/shop.html?id=" + $(this).attr("tip"));
            });
            // 收藏
            $("#btnfavorite").on("click", function () {
                _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
                if (!_currentloginuser) {
                    // 用户若无登录，必须登录
                    redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                    return;
                }
                var current = $(this).find("i");
                if (current.hasClass('icon-love')) {
                    // 收藏
                    current.css("color", "#f4514e")[0].className = "iconfont icon-lovefill";
                    $.ajax({
                        headers: {
                            token: _currentloginuser.token
                        },
                        type: "POST",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/goods/" + _currentloginuser.id + "/" + _goodsId
                    }).done(function (res) {
                        if (AGENT_CLIENT.APP) {
                            plus.webview.getWebviewById("../mine/mylife.html").evalJS("reloadPage()");
                        }
                    }).fail(function (res) {
                        var response = JSON.parse(res.responseText);
                        if (response.Message && response.Message.indexOf("票据") > -1) {
                            $.alert("你的帐号已经在其他地方登录", function () {
                                clearLocalStorage();
                                redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                                return;
                            });
                        }
                    });
                } else {
                    // 取消收藏
                    current.css("color", "#000000")[0].className = "iconfont icon-love";
                    $.ajax({
                        headers: {
                            token: _currentloginuser.token
                        },
                        type: "DELETE",
                        url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/goods/" + _currentloginuser.id + "/" + _goodsId
                    }).done(function (res) {
                    }).fail(function (res) {
                        var response = JSON.parse(res.responseText);
                        if (response.Message && response.Message.indexOf("票据") > -1) {
                            $.alert("你的帐号已经在其他地方登录", function () {
                                clearLocalStorage();
                                redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                                return;
                            });
                        }
                    });
                }
            });
            // 跳转购物车
            $("#btnshopcart").on("click", function () {
                _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
                if (!_currentloginuser) {
                    // 用户若无登录，必须登录
                    redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                    return;
                }
                // 仅上架商品才能加入购物车
                if (1 != _online_sale) {
                    var msginfo = "";
                    if (0 == _online_sale) {
                        msginfo = "该商品为新品，暂未开放购买。请稍后再来！";
                    } else {
                        msginfo = "该商品已下架！";
                    }
                    $.toast(msginfo);
                    return;
                }

                if (AGENT_CLIENT.APP) {
                    var shoppingcartView = plus.webview.create("../shopcart/shoppingcart.html", "shoppingcart.html", {}, {preUrl: "shoppingcart.html"});
                    shoppingcartView.show("pop-in", 300, function () {
                        shoppingcartView.evalJS("shoppingcartPageReady()");
                    });
                } else {
                    redirect("../shopcart/shoppingcart.html?url=shoppingcart.html");
                }
            });
            // 加入购物车
            $("#btnbuy span").on("click", function () {
                _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
                if (!_currentloginuser) {
                    // 用户若无登录，必须登录
                    redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                    return;
                }
                // 仅上架商品才能加入购物车
                if (1 != _online_sale) {
                    var msginfo = "";
                    if (0 == _online_sale) {
                        msginfo = "该商品为新品，暂未开放购买。请稍后再来！";
                    } else {
                        msginfo = "该商品已下架！";
                    }
                    $.toast(msginfo);
                    return;
                }
                $("#btnbuy span[clicked=true]").attr("clicked", false);
                $(this).attr("clicked", true);
                _choosePage.show();
            });
        },
        // 商品相册
        paintGoodsAlbums: function (albums) {
            if (!albums || albums.length == 0) {
                $("#goodspiclist").html("<li><img src='../../images/place/1080x1044.png' /></li>");
                return;
            }
            var html = [];
            $.each(albums, function (i, pic) {
                html.push("<li><img class='lazy' data-original='" + getImageUrl(pic.identify, 1080, 1044) + "' src='../../images/place/1080x1044.png' /></li>");
            })
            $("#goodspiclist").html(html.join(''));
            $(".slider").touchSlider({
                during: 3000,
                autoplay: false,
                showindr: false,
                move: function (currindex, total) {
                    $("#tups").text((currindex + 1) + "/" + total);
                    // 商品图片滑动懒加载
                    $('img.lazy').lazyload({
                        placeholder: "../../images/white.gif",
                        container: $(".slider"),
                        threshold: 100,
                        failure_limit: 10
                    });
                }
            });
            $('img.lazy').lazyload({
                placeholder: "../../images/white.gif",
                container: $(".slider"),
                threshold: 100,
                failure_limit: 10
            });
            $("#tups").text("1/" + $(".slider li").length);
        },
        // 画商品详情
        paintGoodsDetail: function (goodsInfo) {
            var html = [];
            // 商品基本信息
            html.push("<div class='muokuaibg mbtopbottom' style='background:#fff'>");
            html.push("<p class='xfxxqbt'>" + goodsInfo.name + "&nbsp;&nbsp;[" + goodsInfo.specs + "]" + "</p>");
//          if (goodsInfo.Is_coin == 1) {
//              html.push("<p class='cpxqjg'><span class='jinbi'><b><img src='../../images/jbtub.jpg'></b>" + goodsInfo.coin + "</span>+<span class='money' style='text-decoration:none;'>&yen;" + goodsInfo.sku_actprice);
//              html.push("</span>");
//              html.push("</p>");
//          } else {
                html.push("<p class='cpxqjg'>&yen;<label id='promoprice'>" + goodsInfo.shop_price + "</label><span>市场价：" + goodsInfo.market_price + "</span></p>");
//          }
            html.push("</div>");
            // 优惠券
            html.push("<div class='cpxqcx bgbai mbtopbottom mtb5' style='background:#fff'>");
            html.push("<div class='lquan mbbottom' id='couponlist' style='display: none'>");
            html.push("</div>");
            html.push("<div class='cxfsbg mbbottom' id='promolist'>");
            html.push("</div>");
            html.push("<p class='cxfsbt mleft10' id='btnregion'>送至<span>上海 > 长宁区 > 内环以外</span></p>");
            html.push("<p class='cxfsbt storestatus' id='storestatus' style='display:none'>有货</p>");
            html.push("</div>");
            // 商品评价
            html.push("<div class='muokuaibg mbtopbottom mtop5' style='background:#fff'>");
            html.push("<h2 style='margin-left:10px;'  class='xfxianbt mbbottom'>商品评价</h2>");
            html.push("<div id='briefcomments'></div>")
            html.push("<p class='ckgd' id='btnmoreappraise'>查看更多评价<span></span></p>");
            html.push("</div>");
            // 店铺详情
            html.push("<div class='mbtopbottom bgbai mtb5'><div class='dpnybt'>");
            html.push("<p class='dplbytx'><img class='lazy' data-original='" + getImageUrl(goodsInfo.shop_logo, 90, 90) + "'/></p>");
            html.push("<p class='dplbywz'><span>" + goodsInfo.shop_name + "</span><br/><label style='color:rgb(84,84,84);'>" + goodsInfo.sku_nums + "件产品 ▪ " + goodsInfo.sku_favorites + "人关注</label></p>");
            html.push("<p class='dpllyjrdp' id='btnentershop' tip='" + goodsInfo.shop_id + "'>进入店铺</p></div></div>");
            // 店铺介绍，包装规格，售后服务
            html.push("<div class='spxqbg'>");
            html.push("<p class='spxqbt bgbai mbbottom ' id='directionstab'><span class='current' tip='0'>商品介绍</span><span tip='1'>规格参数</span><span tip='2'>包装售后</span></p>");
            html.push(" <div id='currenttab' class='xqbthg'></div>");
            html.push("<div id='tab0' name='tab'>");
            html.push("<div class='spjs' style='width: 100%;margin: 0px'>");
            if (goodsInfo.content) {
                var contenthtml = $("<div></div>");
                var imglist = contenthtml.html(goodsInfo.content).find("img");
                if (imglist && imglist.length > 0) {
                    $.each(imglist, function (i, img) {
                        var imgkey = $(img).attr("src");
                        $(img).attr({
                            "src": '',
                            "data-original": getImageUrl(imgkey, 1080, 510, true)
                        })[0].className = "lazy";
                    });
                }
                html.push(contenthtml.html());
            }
            html.push("</div></div>");
            html.push("<div id='tab1' name='tab' style='display:none'>");
            html.push("<div class='spjs' style='width: 90%;'>");
            if (goodsInfo.Paras && goodsInfo.Paras.length > 0) {
                html.push("<table class='ggcs' border='1px' cellspacing='0px'  bordercolor='#ccc'>");
                html.push("<tr><td class='ggcsleft'></td><td class='ggcsright spscbt'>主体</td></tr>");
                $.each(goodsInfo.Paras, function (i, para) {
                    html.push("<tr><td class='ggcsleft'>" + para.name + "</td><td class='ggcsright'>" + para.value + "</td></tr>");
                })
                html.push("</table>")
            }
            html.push("</div></div>");
            html.push("<div id='tab2' name='tab' style='display:none'>");
            html.push("<div class='spjs' style='width: 90%;'>");
            html.push("<p class='bzqd mbbottom'><span>包装清单：</span><br/>" + goodsInfo.package + "</p>");
            html.push("<p class='fwznbt '>服务承诺</p>");
            html.push("<p class='chengnou'><span>如此生活向您承诺：</span>所售商品均为正品行货，‘如此生活’自营商品开具机打发票或电子发票。凭质保证书及‘如此生活’发票，可享受全国联保服务（奢侈品、钟表除外；奢侈品、钟表由‘如此生活’联系保修，享受法定三包售后服务），与您亲临商场选购的商品享受相同的质量保证。‘如此生活’还为您提供具有竞争力的商品价格和运费政策，请您放心购买！</p>");
            html.push("<p class='chengnou'><span>注：</span>因厂家会在没有任何提前通知的情况下更改产品包装、产地或者一些附件，本司不能确保客户收到的货物与商城图片、产地、附件说明完全一致。只能确保为原厂正货！并且保证与当时市场上同样主流新品一致。若本商城没有及时更新，请大家谅解 </p>");
            html.push("</div></div>");
            html.push("</div>");
            $("#goodsDetailInfo").html(html.join(""));
        },
        // 优惠券
        loadCouponInfo: function (shopId) {
            var model = this;
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/coupon/can/" + shopId
            }).done(function (res) {
                if (!res || res.length == 0) {
                    return;
                }
                var html = []
                html.push("<p class='lquanbt'>领券</p>");
                html.push("<div class='lquanny'>");
                $.each(res, function (i, item) {
                    html.push("<span tip='" + item.coupon_no + "'>&yen;" + item.face_value + "元优惠券</span>");
                });
                html.push("</div>");
                $("#couponlist").html(html.join("")).show();
                // 领卷
                $("#couponlist span").on("click", function () {
                    if (this.className == "liangh") {
                        return;
                    }
                    this.className = "liangh";
                    model.gainCoupon($(this).attr("tip"));
                });
            })
        },
        // 活动
        loadPromoInfo: function (goodsData) {
            var thisPage = this;
            var postdata = {
                "skus": [{
                    "sku_id": _goodsId
                }]
            };
            // 促销活动
            $.ajax({
                headers: {
                    'Content-Type': 'application/json'
                },
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/promo/sku/usable",
                data: JSON.stringify(postdata)
            }).done(function (res) {
            		
            		_choosePage.init(goodsData, res);
            		
                if (res && res.length > 0) {
                  var firstPromo = res[0];
                  if (firstPromo.promo && firstPromo.promo.length > 0) {
                      var html = []
                      html.push("<p class='cxfsbt'>促销<span>可享受的促销方式</span></p>");
                      $.each(firstPromo.promo, function (i, item) {
                          if (item.title) {
                              html.push("<p class='mansong mbbottom'><span>" + item.title + "</span></p>")
                          }
                      });
                      $("#promolist").html(html.join(""));
                      $("#promoprice").html(firstPromo.price);
                      if(firstPromo.coin>0){
                      	$("#promoprice").after("<span class='jinbi' style='text-decoration:none;color:#f08200'><b><img src='../../images/jbtub.jpg'></b><label id='promocoin'>" + firstPromo.coin + "</label></span><span>");
                      }
                      
                  }
                }
                thisPage.existsSuite();
            }).fail(function () {
                thisPage.existsSuite();
            });
        },
        existsSuite: function () {
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/suite/havesuite/" + _goodsId
            }).done(function (res) {
                if (res == true) {
                    var titleTemplate = "";
                    if ($("#promolist").html() == "") {
                        titleTemplate = "<p class='cxfsbt'>促销<span>可享受的促销方式</span></p>";
                    }
                    var suiteTemplate = titleTemplate + "<p class='mansong' id='btnsuite'><a>&nbsp;查看套装活动&nbsp;</a></p>";
                    $("#promolist").append(suiteTemplate);
                    
                }
            });
        },
        // 是否收藏商品
        checkFavorite: function () {
            if (!_currentloginuser) {
                return;
            }
            $.ajax({
                headers: {
                    token: _currentloginuser.token
                },
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/member/favorite/isgoods/" + _currentloginuser.id + "/" + _goodsId
            }).done(function (res) {
                if (res.data == 1) {
                    $("#btnfavorite i").css("color", "#f4514e")[0].className = "iconfont icon-lovefill";
                }
            }).fail(function (res) {
                var response = JSON.parse(res.responseText);
                if (response.message && response.message.indexOf("票据") > -1) {
                    $.alert("你的帐号已经在其他地方登录", function () {
                        clearLocalStorage();
                        redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                        return;
                    });
                }
            });
        },
        // 评论3条数据
        paintComments: function (data) {
            var html = [];
            for (var i = 0; i < data.list.length; i++) {
                var item = data.list[i];
                html.push("<div class='mbbottom xfpinglun'>");
                html.push("<p class='pltxmzsj'><b><img src='" + CONFIG_MANAGER.imgeUrl + item.avatar + "'/></b>" + item.member_name + "<span>" + dateDiff(new Date(item.create_time_text).getTime()) + "</span></p>");
                html.push("<p class='plnr'>" + item.content + "</p>");
                html.push("</div>");
                if (i == 2) {
                    break;
                }
            }
            var count = data.all_count && data.all_count > 0 ? "(" + data.all_count + ")" : "";
            $("#btnmoreappraise span").text(count);
            $("#briefcomments").html(html.join(""));
        },
        // 根据IP送至地址
        getCurrentRegion: function () {
            var model = this;
            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/basic/region/adress/" + $.getIPAddress()
            }).done(function (res) {
                var data = res.data;
                var regionid, regiontext = "";
                if (data.county_no) {
                    regionid = data.county_no;
                } else if (data.city_no) {
                    regionid = data.city_no;
                } else {
                    regionid = data.region_no;
                }
                if (data.region) {
                    regiontext = regiontext + data.region;
                }
                if (data.city) {
                    regiontext = regiontext + " > " + data.city;
                }
                if (data.county) {
                    regiontext = regiontext + " > " + data.county;
                }
                model.checkInventory(regionid, regiontext);
            });
        },
        // 检查库存
        checkInventory: function (regionid, regiontext) {
            $("#detailpage").show();
            if (regionid) {
                $("#btnregion span").text(regiontext).attr("tag", regionid);
                $.ajax({
                    type: "POST",
                    url: CONFIG_MANAGER.RequstUrl + "v1/goods/stocks/" + regionid + "?skuids=" + _goodsId
                }).done(function (res) {
                    var status = (res.data && res.data.length > 0 && res.data[0].iventory > 0) ? "有货" : "无货";
                    $("#storestatus").text(status);
                });
            }
        },
        // 猜你喜欢
        loadloveitemlist: function () {
            var uid = (_currentloginuser) ? _currentloginuser.id : getSessionID();
            $.ajax({
                type: 'GET',
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/rank/like/" + uid + "/" + 6
            }).done(function (res) {
                if (!res || res.length == 0) {
                    return;
                }
                var html = [];
                html.push("<div class='cnxhdbg'><h2 class='cnxhdbiaoti'><span class='bghui'>猜你喜欢</span></h2><ul class='cnxhd' >")
                $.each(res, function (i, goodsitem) {
                    html.push("<li class='syxhd' name='lovegoodsitem' tip='" + goodsitem.sku_id + "'><dl><dt><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 500, 500) + "'  src='../../images/place/500x500.png'></dt><dd>" + goodsitem.name + goodsitem.title + "</dd><dd class='xhmony'>&yen;" + goodsitem.shop_price + "</dd></dl></li>");
                });
                html.push("</ul></div>");
                $("#loveitemlist").html(html.join(""));
                // 懒加载
                $('img.lazy').lazyload({
                    container: _main,
                    event: "scroll",
                    threshold: 100,
                    failure_limit: 10
                });
            });
        },
        // 添加购物车或立即购买
        addbuygoods: function (skuid, qty) {
            _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
            if (!_currentloginuser) {
              redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
              return;
            }
            if ($("#btnbuy span[clicked=true]").attr("tip") == "0") {
                var postdata = {
                    member_id: _currentloginuser.id,
                    session_id: getSessionID(),
                    sku_id: skuid,
                    qty: qty,
                    org_id: CONFIG_MANAGER.orgId,
                };
                $.ajax({
                    type: "POST",
                    url: CONFIG_MANAGER.RequstUrl + "v1/cart/add",
                    data: JSON.stringify(postdata),
                    contentType: 'application/json',
                    headers: {
                        token: _currentloginuser.token
                    },
                    beforeSend: function () {
                        $.showWaiting();
                    }
                }).done(function (res) {
//                  $("#btnshopcart span").text(parseInt($("#btnshopcart span").text()) + 1).show();
                    if (AGENT_CLIENT.APP) {
                        plus.webview.getWebviewById("../shopcart/shoppingcart.html").evalJS("reloadPage()");
                    }
                    //加入购物车之后重新计算商品个数
                    $.ajax({
                        type: "GET",
                        headers: {token: _currentloginuser.token},
                        url: CONFIG_MANAGER.RequstUrl + "v1/cart/sum/" + _currentloginuser.id,
                        async: true,
                    }).done(function (data) {
                        setLocalStorage(STORAGE_MANAGER.cacheproductcount, data.count);
                        $("#btnshopcart span").text(data.count).show();
                        if (AGENT_CLIENT.APP) {
                            plus.webview.getWebviewById("../home/main.html").evalJS("getShopcartProductCount()");
                        }
                    }).always(function (data) {
                        $.closeWaiting();
                    });
                }).always(function (data) {});
            } else {
                //立即购买
                var confirmData = {
                    org_id: CONFIG_MANAGER.orgId,
                    member_id: _currentloginuser.id,
                    address_id: 0,
                    referrer: _currentloginuser.referer,
                    delivery: 1,
                    delivery_point: 3101,
                    instant_buy: 1,
                    share_ids: [_shareId],
                    coupono: '',
                    target_id: [{
                        sku_id: skuid,
                        qty: qty
                    }],
                    supplier: null,
                };
                setLocalStorage(STORAGE_MANAGER.confirmOrderData, confirmData);
                redirect("../shopcart/confirmOrder.html");
            }
        },
        // 领取优惠券
        gainCoupon: function (couponNo) {
            if (!_currentloginuser) {
                // 用户若无登录，必须登录
                redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                return;
            }
            $.ajax({
                headers: {
                    token: _currentloginuser.token
                },
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/member/coupon/gain/" + couponNo + "-" + _currentloginuser.id
            }).done(function (res) {
            }).fail(function (res) {
                var response = JSON.parse(res.responseText);
                if (response.message && response.message.indexOf("票据") > -1) {
                    $.alert("你的帐号已经在其他地方登录", function () {
                        clearLocalStorage();
                        redirect("../account/login.html?backurl=goods|goodsdetail.html" + window.location.search);
                        return;
                    });
                }
                $.toast(response.Message);
            });
        },
        // 浏览记录
        addhistory: function () {
            if (!_currentloginuser) {
                return;
            }
            var postdata = {
                member_id: _currentloginuser.id,
                session_id: getSessionID(),
                sku_id: _goodsId
            };
            $.ajax({
                headers: {
                    'Content-Type': 'application/json'
                },
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/history",
                data: JSON.stringify(postdata),
            }).always(function (res) {
            });
        },
        // 添加扫描历史纪录
        addBarcodeHistory: function (data) {
            if (!_barcodetype) {
                return;
            }
            var barcodehistory = getLocalStorage(STORAGE_MANAGER.barcodehistory);
            if (!barcodehistory) {
                barcodehistory = [];
            }
            barcodehistory.push({
                type: _barcodetype,
                result: _goodsId,
                logo:data.logo,
                desc: data.name + data.specs + data.title,
                create_time: new Date().getTime()
            });
            console.log(JSON.stringify(barcodehistory));
            setLocalStorage(STORAGE_MANAGER.barcodehistory, barcodehistory);
        },
        // 判断显示置顶图标
        isDisplayTopIcon: function (y) {
            var top = _main.scrollTop();
            if (top > _contentheight / 2) {
                $("#gotop").show();
            } else {
                $("#gotop").hide();
            }
        },
    };
    // 商品选择页面
    var _choosePage = new choosePage();
    // 评价页面
    var _goodsCommentsPage = new goodsCommentsPage();
    // 详情页面
    var _goodsDetailPage = new goodsDetailPage();
    // 分享页面
    var _sharePage = new sharePage();
    // 评价回退
    _goodsCommentsPage.back = function () {
        _goodsCommentsPage.hide();
        $("#detailpage").show();
    }
    _goodsCommentsPage.initEnd = function (data) {
        _goodsDetailPage.paintComments(data);
    }
    // 区域页面
    var _regionPage = new regionPage();
    _regionPage.getResult = function (regionid, regiontext) {
        _goodsDetailPage.checkInventory(regionid, regiontext);
    }
    // 商品选择确认
    _choosePage.confirm = function (skuid, qty) {
        _goodsDetailPage.addbuygoods(skuid, qty);
    }
}
// 关闭搜索页
function showSearchPage() {
    $("#searchiframe").show();
    searchiframe.window.loadSearchHistory();
}
// 关闭搜索页
function closeSearchPage() {
    $("#searchiframe").hide();
}

function getShopcartProductCount(){
	var count = getLocalStorage(STORAGE_MANAGER.cacheproductcount);
	if(count && count>0){
		$("#btnshopcart span").show().text(count);
	}else{
		$("#btnshopcart span").hide();
	}	
}
